package br.embedded.socialapp.location;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;


import br.embedded.socialapp.business.FriendManager;
import br.embedded.socialapp.business.UserManager;
import br.embedded.socialapp.data.DataFacade;
import br.embedded.socialapp.domain.User;
import br.embedded.socialapp.domain.Usuario;
import br.embedded.socialapp.exceptions.UserException;

public class LocationManager {

	private static LocationManager singleton;
	private static DataFacade dataFacade;
	
	private LocationManager()
	{
		dataFacade = DataFacade.getInstance();
	}
	
	public static LocationManager getInstance()
	{
		if (singleton == null)
			singleton = new LocationManager();
		return singleton;
	}
	
	public void registerLocation(String login, double latitude, double longitude)
	{
		dataFacade.registerLocation(login, latitude, longitude);
	}
	
	public List<Coordenates> getNearestUsers(Coordenates userCoordenates, Date initialDate, Date endDate,
			double maxDistance)
	{
		try {
			String login = userCoordenates.getUserLogin();
			Usuario usuario = UserManager.getInstance().getUserByLogin(login);
			
			List<User> friendList = FriendManager.getInstance().getFriends(usuario);
			List<Usuario> registeredFriends = UserManager.getInstance().getUserById(getIds(friendList));
			List<Coordenates> friendsCoordenates = dataFacade.getCoordenates(registeredFriends, initialDate, endDate);
			
			return searchNearestUsers(userCoordenates, friendsCoordenates, maxDistance);
			
		} catch (UserException e) {
			e.printStackTrace();
		}
		return null;
	}

	private List<Coordenates> searchNearestUsers(Coordenates userCoordenates, List<Coordenates> friendsCoordenates, double maxDistance)
	{
		Hashtable<String, Coordenates> users = new Hashtable<String, Coordenates>();
		
		for (Coordenates friendCoordenates : friendsCoordenates)
		{
			if (!users.containsKey(friendCoordenates.getUserLogin()))
			{
				double distance = LocationHandler.calculateDistance(userCoordenates, friendCoordenates);
				
				if (distance <= maxDistance)
				{
					friendCoordenates.setDistance(distance);
					users.put(friendCoordenates.getUserLogin(), friendCoordenates);
				}
			}
		}
		
		List<Coordenates> listCoordenates = new ArrayList<Coordenates>(users.values()); 
		
		Collections.sort(listCoordenates, new CoordenatesComparator());
		
		return listCoordenates;
	}
	
	private String getIds(List<User> list)
	{
		StringBuffer sb = new StringBuffer();
		
		if (list != null && list.size() > 0)
		{
			for (int i = 0; i < list.size(); i++) {
				sb.append("'");
				sb.append(list.get(i).getId());
				sb.append("',");
			}
			return sb.deleteCharAt(sb.length() -1).toString();
		}
		return "";
	}
}
